package org.yuci.concurency.interrupt.case01;

/**
 * http://www.tutorialspoint.com/javaexamples/thread_interrupt.htm
 *
 */
public class GeneralInterrupt extends Object implements Runnable {
    private int workId;
    
    public void run() {
        try {
            System.out.println("in run() - about to work " + workId);
            if (workId == 1) {
                work1();
            } else if (workId == 2) {
                work2();
            } else {
                work1();
            }
            System.out.println("in run() - back from  work " + workId);
        } catch (InterruptedException x) {
            System.out.println("in run() - interrupted in work " + workId);
            return;
        }
        System.out.println("in run() -  doing stuff after nap");
        System.out.println("in run() - leaving normally");
    }

    public void work1() throws InterruptedException {
        while (true) {
            for (int i = 0; i < 1_000_000; i++) {
                int j = i * 2;
            }
            if (Thread.currentThread().isInterrupted()) {
                System.out.println("A isInterrupted()=true");
            }
            
            if (Thread.currentThread().isInterrupted()) {
                System.out.println("A isInterrupted()=true still");
            }
            
            if (Thread.interrupted()) {
                System.out.println("B isInterrupted()=" + Thread.currentThread().isInterrupted());
                throw new InterruptedException();
            }
        }
    }
    
    public void work2() throws InterruptedException {
        while (true) {
            if (Thread.currentThread().isInterrupted()) {
                System.out.println("C isInterrupted()=" + Thread.currentThread().isInterrupted());
                Thread.sleep(2000);
                System.out.println("D isInterrupted()=" + Thread.currentThread().isInterrupted());
            }
        }
    }

    public int getWorkId() {
        return workId;
    }

    public void setWorkId(int workId) {
        this.workId = workId;
    }
}